package net.piggy.file.controller;

import net.piggy.file.domain.FileBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);
    private static final String TEMP_DIR = "D:\\code\\file\\temp";
    private static final String SAVE_DIR = "D:\\code\\file\\save";

    @PostMapping("/uploadChunk")
    public ResponseEntity<String> uploadChunk(@RequestParam("file") MultipartFile file,
                                              @RequestParam("chunkIndex") int chunkIndex,
                                              @RequestParam("identifier") String identifier) throws IOException {
        // 创建临时目录
        File tempDir = new File(TEMP_DIR, identifier);
        if (!tempDir.exists()) {
            boolean mkdirs = tempDir.mkdirs();
            LOGGER.info("number one " + tempDir.getPath() + " -> " + mkdirs);
        }

        // 将分片文件保存到临时目录
        File chunkFile = new File(tempDir, String.valueOf(chunkIndex));
        file.transferTo(chunkFile);

        return ResponseEntity.ok("chunk " + chunkIndex + " uploaded successfully.");
    }

    @PostMapping("/mergeChunks")
    public ResponseEntity<String> mergeChunks(@RequestBody FileBody fileBody) throws IOException {

        int totalChunks = fileBody.getTotalChunks();
        long identifier = fileBody.getIdentifier();
        String fileName = fileBody.getFileName();
        // 获取分片目录
        File tempDir = new File(TEMP_DIR, String.valueOf(identifier));
        File[] files = tempDir.listFiles();
        if (!tempDir.exists() || files == null || files.length != totalChunks) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("incomplete chunks.");
        }

        // 合并分片
        File finalFile = new File(SAVE_DIR, fileName);
        try (FileOutputStream outputStream = new FileOutputStream(finalFile)) {
            for (int i = 0; i < totalChunks; i++) {
                File chunkFile = new File(tempDir, String.valueOf(i));
                Files.copy(chunkFile.toPath(), outputStream);
                boolean delete = chunkFile.delete();
                LOGGER.info("number two " + finalFile.getPath() + " -> " + delete);
            }
        }

        // 删除临时目录
        boolean delete = tempDir.delete();
        LOGGER.info("number three " + tempDir.getPath() + " -> " + delete);
        return ResponseEntity.ok("file merged successfully.");
    }
}

